package com.fingard.dsp.bank.directbank.sdebank01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

import java.util.Date;
import java.util.Random;

/**
 * @author: liuxb
 * @create: 2019-12-02 14:29
 * @version: 1.0
 **/
public class SDEBANK01Base extends DirectBase {
    protected static final String INSERTSEQONE = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    protected static final String INSERTSEQTWO = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID,BANKREQBATCHNO) values (?,?,?,?,?,?);";
    protected static final String SELECTSEQONE = "SELECT BANKREQSEQID FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";
    protected static final String SELECTSEQTWO = "SELECT BANKREQSEQID,BANKREQBATCHNO FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";

    protected static TransIDHelper idHelper = new TransIDHelper(1, 9999);

    protected static String splitToString="#*#";//备注拼接符

    /**
     * 获取交互字符集
     *
     * @return
     **/
    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    /**
     * 写通用公共报文头
     */
    protected void writeCommonHeader(XmlTextWriter xmlWriter, SDEBANK01Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.TrsCode)) {
            throw new Exception("未赋值serviceId");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\"?>");
        xmlWriter.writeStartElement("Message");
        xmlWriter.writeStartElement("Head");
        xmlWriter.writeElementString("TrsCode", p_bankHeader.TrsCode);//银行交易码，用以区分不同的操作
        Date tmpDateNow = new Date();
        xmlWriter.writeElementString("ERPTrsTimestamp", Format.DateTime14Format.format(tmpDateNow));//交易时间(格式为：yyyyMMddHHmmss)
        xmlWriter.writeElementString("ERPJnlNo ", p_bankHeader.ERPJnlNo);//ERP（财务系统）交易流水号
        xmlWriter.writeElementString("TrsFlag ", p_bankHeader.TrsFlag);//交易标志 0:正常交易，1：重发交易
        xmlWriter.writeEndElement();
    }

    /**
     * 发送银行前置
     *
     * @param p_reqStr
     * @return
     * @throws Exception
     */

    protected String[] sendToBank(String p_reqStr, SDEBANK01Header header) throws Exception {
        String[] result = {"", ""};
        String tmpUrl = bankFront.serverURL + header.TrsCode + ".do?userPassword=" + bankFront.userPassword + "&SIGDATA=1";
        WriteBankLogLn("1.提交银行的地址：" + tmpUrl);
        WriteBankLogStep2(p_reqStr);
        WebRequest tmpWebRequest = new WebRequest(tmpUrl);
        tmpWebRequest.setConnectTimeout(100000);//设置连接超时
        tmpWebRequest.setRequestProperty("Method", "POST");//设置请求属性
        tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置请求属性
        tmpWebRequest.setRequestProperty("connection", "close");//设置连接状态
        byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
        result = tmpWebRequest.upload(tmpUpBytes, getCharset());
        WriteBankLogStep3(result[1]);
        return result;
    }

//    protected String[] sendToBank(String p_reqStr) throws Exception {
//        String[] retStr = new String[]{"", ""};
//        String tmpUrl = bankFront.serverURL;
//        WriteBankLogLn("1.提交银行的地址：" + tmpUrl);
//        WriteBankLogStep2(p_reqStr);
//        WebRequest tmpWebRequest = new WebRequest(tmpUrl);//Http通讯用WebRequest
//        tmpWebRequest.setConnectTimeout(60000);
//        tmpWebRequest.setRequestProperty("Method", "POST");
//        tmpWebRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
//        tmpWebRequest.setRequestProperty("connection", "close");//设置连接状态
//        byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
//        retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
//        WriteBankLogStep3(retStr[1]);
//        return retStr;
//
//    }

    /**
     * 生成指定位数的随机整数
     * 如果指定位数不足两位，均返回十以内的整数
     *
     * @param size 位数（需大于零）
     * @return 随机整数 *
     */
    public static int random(int size) {
        Random random = new Random();
        if (size < 2) {
            return random.nextInt(10);
        }
        Double pow = Math.pow(10, size - 1);
        int base = pow.intValue();
        int number = base + random.nextInt(base * 9);
        return number;
    }

    /**
     * 生成唯一交易流水号:2位数+6位年月日+3位数
     *
     * @return
     */
    protected String getTrmSeqNum() {
        Date tmpDateNow = new Date();
        return random(2) + Format.Date6Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected String getQryTransID() {
        return Format.DateTime12Year2Format.format(new Date()) + idHelper.getNextIDStr();
    }

    /**
     * 提取字符串中的数字
     */
    public static String sub(String str) {
        str = str.trim();
        String str2 = "";
        if(str != null &&!"".equals(str)){
            for (int i=0;i<str.length();i++){
                if (str.charAt(i)>=48 && str.charAt(i)<=57){
                    str2 += str.charAt(i);
                }
            }
        }
        return  str2;
    }

    protected String convertOptCodeToBank(String p_curATS) throws Exception {
        return getBankConfig().getMapValueByKey("OptCodeMapping", p_curATS);
    }

    // 业务类型 1-出票 2-承兑 3-收票 4-背书转让 5-质押 6-解质押 7-出票保证
    // 8-承兑保证 9-背书保证 10-贴现 11-回购式贴现赎回 12-提示付款 13-追索 14-同意清偿
    protected String getBusiType(String operType,String busiTypes) throws Exception{
        //电票交易类型
        String busiType = "";
        if ("1".equals(operType)) {
            switch (Integer.valueOf(busiTypes)) {
                case 1: busiType = "0000";break;
                case 2: busiType = "0001";break;
                case 3: busiType = "0002";break;
                case 4: busiType = "0004";break;
                case 5: busiType = "0006";break;
                case 6: busiType = "0007";break;
                case 10: busiType = "0005";break;
                case 12: busiType = "0008";break;
                case 13: busiType = "0009";break;
                case 14: busiType = "0010";break;
                default: throw new Exception("不支持的申请查询类型：" + operType);
            }
        } else if ("4".equals(operType)) {
            switch (Integer.valueOf(busiTypes)) {
                case 1: busiType = "0014";break;//出票撤回
                case 2: busiType = "0015";break;//承兑撤回
                case 3: busiType = "0016";break;//交票撤回
                case 4: busiType = "0017";break;//背书撤回
                case 10: busiType = "0018";break;//贴现撤回

                case 5: busiType = "0019";break;//质押撤回
                case 6: busiType = "0020";break;//质押解除撤回

                case 12: busiType = "0021";break;//提示付款撤回
                case 13: busiType = "0022";break;
                case 14: busiType = "0023";break;
                default: throw new Exception("不支持的撤销查询类型：" + operType);
            }
        }
        return busiType;
    }

    /**
     * 票据类型 1=AC01=银票  2=AC02=商票
     * @param billType
     * @return
     */
    protected String getBillType(String billType){
        String result="";
        if("AC01".equals(billType) || "AC02".equals(billType)){
            result= "AC01".equals(billType) ? "1" : "2";
        }else if("1".equals(billType) || "2".equals(billType)){
            result= "1".equals(billType) ? "AC01" : "AC02";
        }
        return result;
    }

    /**
     * 转让标志 1=EM00=可转让  0=EM01=不可转让
     * @param transFlag
     * @return
     */
    protected String getTransFlag(String transFlag){
        String result="";
        if("EM00".equals(transFlag) || "EM01".equals(transFlag)){
            result= "EM00".equals(transFlag) ? "1" : "0";
        }else if("1".equals(transFlag) || "0".equals(transFlag)){
            result= "1".equals(transFlag) ? "EM00" : "EM01";
        }
        return result;
    }

    /**
     * 清算标志 1=SM00=线上  2=SM01=线下
     * @param payType
     * @return
     */
    protected String getPayType(String payType){
        String result="";
        if("SM00".equals(payType) || "SM01".equals(payType)){
            result= "SM00".equals(payType) ? "1" : "2";
        }else if("1".equals(payType) || "2".equals(payType)){
            result= "1".equals(payType) ? "SM00" : "SM01";
        }
        return result;
    }

    /**
     * 签收标志  SU00同意签收  SU01拒绝签收
     * @param respFlag
     * @return
     */
    protected String getRespFlag(String respFlag){
        String result="";
        if("SU00".equals(respFlag) || "SU01".equals(respFlag)){
            result= "SU00".equals(respFlag) ? "1" : "2";
        }else if("1".equals(respFlag) || "2".equals(respFlag)){
            result= "1".equals(respFlag) ? "SU00" : "SU01";
        }
        return result;
    }

    /**
     * 签收标志  1=RM00买断式  2=RM01回购式
     * @param discType
     * @return
     */
    protected String getDiscType(String discType){
        String result="";
        if("RM00".equals(discType) || "RM01".equals(discType)){
            result= "RM00".equals(discType) ? "1" : "2";
        }else if("1".equals(discType) || "2".equals(discType)){
            result= "1".equals(discType) ? "RM00" : "RM01";
        }
        return result;
    }

    /**
     * 签收标志  1=RT00拒付追索  2=RT01非拒付追索
     * @param recourseType
     * @return
     */
    protected String getRecourseType(String recourseType){
        String result="";
        if("RT00".equals(recourseType) || "RT01".equals(recourseType)){
            result= "RT00".equals(recourseType) ? "1" : "2";
        }else if("1".equals(recourseType) || "2".equals(recourseType)){
            result= "1".equals(recourseType) ? "RT00" : "RT01";
        }
        return result;
    }
}
